package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.AuthorService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.message.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    /**
     * 根据文章Id保存文章
     * @param newsId 文章id
     */
    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    GeneratePageService generatePageService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void publishArticle(Integer newsId) {
        //校验数据合法性
        if (newsId == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据id查询文章
        WmNews wmNews = wemediaFeign.updateNews(newsId).getData();
        //判断状态
        chekWmNews(wmNews);
        //封装文章信息
        ApArticle article = getApArticle(wmNews);
        // 3. 保存或修改 article信息
        saveOrUpdateArticle(article);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, article);
        // 5. 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateWmNews(newsId, wmNews, article);
        // 7. 通知es索引库添加文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",article.getId());
    }

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        //3 返回结果
        // 添加静态页面访问前缀  ===============新增代码=================
        for (ApArticle apArticle : articleList) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        return result;
    }

    /**
     * 根据id查询article
     * @param id
     */
    @Override
    public ResponseResult<SearchArticleVO> findArticle(Long id) {
        ApArticle article = this.getById(id);
        if (article != null){
            SearchArticleVO searchArticleVO = new SearchArticleVO();
            BeanUtils.copyProperties(article, searchArticleVO);
            return ResponseResult.okResult(searchArticleVO);
        }
        return null;
    }

    private void saveOrUpdateArticle(ApArticle apArticle) {
        // 判断wmNews之前是否关联 articleId
        if(apArticle.getId() == null){
            // 无关联  新增 article
            // 保存文章
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            save(apArticle);
        }else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle article = getById(apArticle.getId());
            if(article == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章不存在");
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
        }
    }

    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult updateResult = wemediaFeign.updateWmNews(wmNews);
        if (!updateResult.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章接口失败");
        }
    }

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        // 添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 添加文章详情
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    @Autowired
    AuthorService authorService;

    @Autowired
    AdminFeign adminFeign;

    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        // 拷贝属性
        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte)0); // 普通文章
        apArticle.setLayout(wmNews.getType());// 布局
        //设置作者姓名姓名
        ApAuthor author = authorService.findApAuthorByUserId(wmNews.getUserId());
        //判断作者信息
        if (author == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.error("根据userId查询作者出错,当前作者不存在,userid===>{}",wmNews.getUserId());
        }
        //设置作者信息
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());
        //设置频道信息跟名称
        ResponseResult<AdChannel> ad = adminFeign.findOne(wmNews.getChannelId());
        //判断频道是否存在
        AdChannel adChannel = ad.getData();
        if (adChannel == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.error("查询频道不存在,频道id===={}",wmNews.getChannelId());
        }
        //设置频道信息
        apArticle.setChannelId(adChannel.getId());
        apArticle.setChannelName(adChannel.getName());
        //封装结果返回
        return apArticle;
    }

    /**
     * 检查状态
     * @param wmNews
     */
    private void chekWmNews(WmNews wmNews) {
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章状态是否通过
        if (wmNews.getStatus() != 4 && wmNews.getStatus() != 8){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章未通过审核");
            log.error("文章状态不通过,当前文章Id{}",wmNews.getId());
        }
    }
}